package com.example.nonggo.view.act;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.activity.OnBackPressedCallback;
import androidx.activity.OnBackPressedDispatcher;
import androidx.appcompat.app.AppCompatActivity;

import com.allen.library.RxHttpUtils;
import com.allen.library.interceptor.Transformer;
import com.allen.library.observer.CommonObserver;
import com.example.nonggo.Constants;
import com.example.nonggo.R;
import com.example.nonggo.api.BaseApi;
import com.example.nonggo.api.MDataObserver;
import com.example.nonggo.bean.AverageByDateDTO;
import com.example.nonggo.bean.GoodsPrice;
import com.example.nonggo.bean.GoodsPriceDTO;
import com.example.nonggo.bean.PriceAverageByDateVO;
import com.example.nonggo.utils.CustomToastUtils;
import com.github.mikephil.charting.charts.LineChart;
import com.github.mikephil.charting.components.LimitLine;
import com.github.mikephil.charting.components.XAxis;
import com.github.mikephil.charting.components.YAxis;
import com.github.mikephil.charting.data.Entry;
import com.github.mikephil.charting.data.LineData;
import com.github.mikephil.charting.data.LineDataSet;
import com.github.mikephil.charting.formatter.ValueFormatter;
import com.github.mikephil.charting.interfaces.datasets.ILineDataSet;
import com.github.mikephil.charting.utils.ColorTemplate;
import com.tencent.mmkv.MMKV;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

public class AssistantDetailActivity extends AppCompatActivity {
    private LineChart chart;
    private String varietyName;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        setContentView(R.layout.activity_assistant_detail);

        getWindow().setNavigationBarColor(Color.TRANSPARENT);
        // 隐藏状态栏
        getWindow().getDecorView().setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_FULLSCREEN | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);

        varietyName = getIntent().getStringExtra("varietyName");
        TextView variety = findViewById(R.id.variety);
        variety.setText(String.format("品种：%s", varietyName));
        chart = findViewById(R.id.lineChart);
        initChart(chart);
        getData(varietyName);
        TextView todayPrice = findViewById(R.id.today_price);
        todayPrice.setOnClickListener(v -> {
            // 跳转到详情
            Intent intent = new Intent(this, VarietyPriceListActivity.class);
            intent.putExtra("varietyName", varietyName);
            startActivity(intent);
        });
        // 设置Back按钮的点击事件
        ImageButton backButton = findViewById(R.id.back_button);
        // 获取 OnBackPressedDispatcher
        OnBackPressedDispatcher dispatcher = getOnBackPressedDispatcher();
        dispatcher.addCallback(this, new OnBackPressedCallback(true) {
            @Override
            public void handleOnBackPressed() {
                myBackPressed();
            }
        });
        backButton.setOnClickListener(v -> this.myBackPressed());
    }

    private void myBackPressed() {
        finish();
    }

    /**
     * 初始化图表样式和配置
     *
     * @param chart 图表对象
     */
    private void initChart(LineChart chart) {
        {
            // background color
            chart.setBackgroundColor(Color.WHITE);
            // disable description text
            chart.getDescription().setEnabled(false);
            // enable touch gestures
            chart.setTouchEnabled(true);
            chart.setDrawGridBackground(false);
            // enable scaling and dragging
            chart.setDragEnabled(false);
            chart.setScaleEnabled(false);
            // force pinch zoom along both axis
            chart.setPinchZoom(true);
        }

        XAxis xAxis;
        {   // // X-Axis Style // //
            xAxis = chart.getXAxis();
            xAxis.setPosition(XAxis.XAxisPosition.BOTTOM);
            xAxis.setGranularity(1f);
            xAxis.setLabelCount(7);
            xAxis.setTextSize(20f);
        }

        YAxis yAxis;
        {   // // Y-Axis Style // //
            yAxis = chart.getAxisLeft();
            chart.getAxisRight().setEnabled(false);
            yAxis.setAxisMaximum(40f);
            yAxis.setAxisMinimum(0f);
            yAxis.setTextSize(20f);
            LimitLine llXAxis = new LimitLine(9f, " ");
            llXAxis.setLineWidth(1f);
            llXAxis.setLabelPosition(LimitLine.LimitLabelPosition.LEFT_BOTTOM);
            llXAxis.setTextSize(28f);
            yAxis.setDrawLimitLinesBehindData(false);
            xAxis.setDrawLimitLinesBehindData(false);
            xAxis.setDrawGridLines(false);
        }
        // 初始化 数据
        ArrayList<Entry> values = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            values.add(new Entry(i, 0.0F, null));
        }
        // create a dataset and give it a type
        LineDataSet set1 = new LineDataSet(values, " ");
        set1.setCubicIntensity(1.0f);
        //数据对应的是左边还是右边的Y值
        set1.setAxisDependency(YAxis.AxisDependency.LEFT);
        //线条的颜色
        set1.setColor(ColorTemplate.rgb("9784B9"));
        //表中数据圆点的颜色
        set1.setCircleColor(ColorTemplate.rgb("9784B9"));
        //表中数据线条的宽度
        set1.setLineWidth(2f);
        //表中数据圆点的半径
        set1.setCircleRadius(3f);
        set1.setValueTextSize(20F);
        set1.setValueTextColor(ColorTemplate.rgb("333333"));
        //设置线面部分是否填充
        set1.setDrawFilled(true);
        //填充的颜色透明度
        set1.setFillAlpha(255);
        //填充颜色
        set1.setFillColor(ColorTemplate.rgb("9784B9"));
        set1.setHighLightColor(Color.rgb(244, 117, 117));
        //绘制的数据的圆点是否是实心还是空心
        set1.setDrawCircleHole(false);
        ArrayList<ILineDataSet> dataSets = new ArrayList<>();
        dataSets.add(set1);
        LineData data = new LineData(dataSets);
        chart.setData(data);
    }


    private void updatePrice(GoodsPrice goodsPrice) {
        TextView minView = findViewById(R.id.minimum_price);
        TextView midView = findViewById(R.id.middle_price);
        TextView higView = findViewById(R.id.highest_price);
        TextView variety = findViewById(R.id.variety);
        variety.setText(String.format("品种：%s", varietyName));
        minView.setText(String.format("最低价\n%s", goodsPrice.getMinimumPriceCurrentList()));
        midView.setText(String.format("平均价\n%s", goodsPrice.getMiddlePriceCurrentList()));
        higView.setText(String.format("最高价\n%s", goodsPrice.getHighestPriceCurrentList()));
    }

    private void getData(String varietyName) {
        String token = MMKV.defaultMMKV().getString(Constants.ACCESS_TOKEN, "0");
        BaseApi api = RxHttpUtils.createApi(BaseApi.class);
        api.getGoodsPrice(token, new GoodsPriceDTO(varietyName).toRequestBody())
                .compose(Transformer.switchSchedulers(null))
                .subscribe(new MDataObserver<>() {
                    @Override
                    protected void onSuccess(GoodsPrice data) {
                        if (data == null || data.getMiddlePriceCurrentList() == null) {
                            empty();
                            return;
                        }
                        updatePrice(data);
                    }

                    @Override
                    public void doOnError(String errorMsg) {
                        empty();
                    }
                });

        api.getAverageByDate(token, new AverageByDateDTO(varietyName).toRequestBody())
                .compose(Transformer.switchSchedulers(null))
                .subscribe(new CommonObserver<>() {
                    @Override
                    protected void onError(String errorMsg) {
                        CustomToastUtils.showCustomToast("获取详情失败，请稍后再试");
//                        Log.e("TAG", "accept:errorMsg===> " + errorMsg);
                    }

                    @Override
                    protected void onSuccess(List<PriceAverageByDateVO> priceAverageByDateVOS) {

                        if (priceAverageByDateVOS == null || priceAverageByDateVOS.isEmpty()) {
                            return;
                        }
                        ArrayList<Entry> values = new ArrayList<>();
                        List<String> dates = new ArrayList<>();
                        float max = 0F;
                        int size = Math.max(3, priceAverageByDateVOS.size());
//                        xAxis.setValueFormatter(new WeatherDetailActivity.DateAxisFormatter(dates));
                        for (int i = 0; i < size; i++) {
                            if (i >= priceAverageByDateVOS.size()) {
                                values.add(new Entry(i, 0.0F, null));
                            } else {
                                PriceAverageByDateVO vo = priceAverageByDateVOS.get(i);
                                if (vo.getMiddlePrice() > max) {
                                    max = vo.getMiddlePrice();
                                }
                                String date = Optional.ofNullable(vo.getReportTime()).orElse("0000-0");
                                String day = date.substring(5, date.length() - 1);
                                dates.add(day);
                                values.add(new Entry(i, vo.getMiddlePrice(), null));
                            }
                        }
                        chart.getXAxis().setValueFormatter(new ValueFormatter() {
                            @Override
                            public String getFormattedValue(float value) {
                                int index = (int) value;
                                if (index >= 0 && index < dates.size()) {
                                    return dates.get(index);
                                }
                                return "";
                            }
                        });
                        chart.getAxisLeft().setAxisMaximum(max + ((max + 1) / 8 + 3));
                        if (chart.getData() != null && chart.getData().getDataSetCount() > 0) {
                            LineDataSet set1 = (LineDataSet) chart.getData().getDataSetByIndex(0);
                            set1.setValues(values);
                            set1.notifyDataSetChanged();
                            chart.getData().notifyDataChanged();
                            chart.notifyDataSetChanged();
                            chart.invalidate();
                        }
                    }
                });

    }

    private void empty() {
        GoodsPrice goodsPrice = new GoodsPrice();
        goodsPrice.setVarietyName(varietyName);
        goodsPrice.setMinimumPriceCurrentList(0F);
        goodsPrice.setMiddlePriceCurrentList(0F);
        goodsPrice.setHighestPriceCurrentList(0F);
        updatePrice(goodsPrice);
    }
}